package org.zero.manager.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.zero.config.AlipayProperties;
import org.zero.manager.AlipayManager;
import org.zero.model.AlipayRequest;

/**
 * @author Zero (cnzeropro@qq.com)
 * @date 2021/10/5 17:53
 */
@Service("alipayManager")
@Slf4j
public class AlipayManagerImpl implements AlipayManager {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public String pay(AlipayRequest alipayRequest) throws AlipayApiException, JsonProcessingException {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置异步通知路径
        request.setNotifyUrl(AlipayProperties.notifyUrl);
        // 设置同步通知路径
        request.setReturnUrl(AlipayProperties.returnUrl);

        // 使用Jackson ObjectMapper转成json字串封装
        // request.setBizContent(objectMapper.writeValueAsString(alipayRequest));

        // 手动封装便于了解封装的信息
        AlipayTradePagePayModel bizModel = new AlipayTradePagePayModel();
        bizModel.setOutTradeNo(alipayRequest.getOutTradeNo());
        bizModel.setSubject(alipayRequest.getSubject());
        bizModel.setTotalAmount(alipayRequest.getTotalAmount());
        bizModel.setProductCode(alipayRequest.getProductCode());
        bizModel.setQrPayMode(alipayRequest.getQrPayMode());
        bizModel.setQrcodeWidth(alipayRequest.getQrcodeWidth());
        bizModel.setTimeExpire(alipayRequest.getTimeExpire());
        bizModel.setTimeoutExpress(alipayRequest.getTimeoutExpress());
        bizModel.setGoodsDetail(alipayRequest.getGoodsDetail());
        request.setBizModel(bizModel);

        // 支付宝第一次请求响应
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);

        if (response.isSuccess()) {
            // 响应体（html字符串）发送到前端进行二次请求（包含的form表单自动进行二次请求）
            return response.getBody();
        }
        return null;
    }
}
